/**
 * AccountService.java
 */
package com.rgh.pecunia.core.rest;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.rgh.pecunia.core.DataAccessObject;
import com.rgh.pecunia.core.PecuniaBusiness;
import com.rgh.pecunia.core.dao.ObjectifyDAO;
import com.rgh.pecunia.domain.Account;

/**
 * 
 * @author javabeats@gmail.com
 */
@Path("/account/")
public class AccountService {

	@POST
	@Path("/add")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
	public Account add(@FormParam("name") String name) {

		// Help objects
		DataAccessObject dao = new ObjectifyDAO();
		PecuniaBusiness biz = new PecuniaBusiness(dao);

		// Entity instance
		Account a = new Account();
		a.setName(name);
		a.setKey(biz.generateAccountKey());
		dao.put(a);

		return a;
	}

	@GET
	@Path("/sync")
	@Produces({ MediaType.APPLICATION_JSON })
	public JSONArray sync() {
		DataAccessObject dao = new ObjectifyDAO();
		JSONArray array = new JSONArray();
		try {
			List<Account> accounts = dao.query(Account.class).list();
			for (Account account : accounts) {
				JSONObject obj = new JSONObject();
				obj.put("key", account.getKey());
				obj.put("name", account.getName());
				obj.put("balance", account.getBalance());
				array.put(obj);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return array;
	}
}
